/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */

struct Node* copyRandomList(struct Node* head) {
	struct Node* cur = head;//cur遍历原链表
    struct Node* next = NULL;//next是cur的下一个
    struct Node* copy = NULL;//指向复制链表中节点
    //拷贝节点在原节点的后面
    while(cur)
    {
        next = cur->next;
        copy = (struct Node*)malloc(sizeof(struct Node));
        copy->val = cur->val;
        //插入
        copy->next = next;
        cur->next = copy;
        //迭代
        cur = next;
    }
    //第二步
    cur = head;
    while(cur)
    {        
        copy = cur->next;
        next = copy->next;
        if(cur->random)
        {
            //修改random
            copy->random = cur->random->next;
        }
        else
        {
            copy->random = NULL;
        }
        cur = next;
    }
    //第三步
    cur = head;
    struct Node* copyhead = NULL;
    while(cur)
    {
        copy = cur->next;
        next = copy->next;
        //
        if(copyhead == NULL)
        {
            copyhead = copy;
        }
        if(next){
            copy->next = next->next;
        }
        cur->next = next;
        cur = next;
    }
    return copyhead;
}